package com.ithanwen.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * Created By tony
 * <br/>Date: 2025/7/11 14:51
 * <br/>Description:
 */
@Component
public class OSSUtils {

    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;
    /**
     * 上传文件到OSS
     *
     * @param file       要上传的文件对象
     * @param objectName OSS 中保存的路径+文件名
     */
    // @Value("${aliyun.oss.endpoint}")
    // private String endpoint;
    // @Value("${aliyun.oss.bucketName}")
    // private String bucketName;
    // @Value("${aliyun.oss.region}")
    // private String region;

    public String uploadFile(MultipartFile file, String objectName) throws ClientException {
        String endpoint = aliyunOSSProperties.getEndpoint();
        String bucketName = aliyunOSSProperties.getBucketName();
        String region = aliyunOSSProperties.getRegion();
        // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();

        try {
            File tempFile = File.createTempFile("upload-", ".tmp");
            file.transferTo(tempFile);
            ossClient.putObject("java-tl1as", objectName, tempFile);
            System.out.println("文件 " + objectName + " 上传成功。");
        } catch (Exception e) {
            System.err.println("文件上传失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com" + "/" + objectName;
    }
}